package cn.stylefeng.guns.modular.replenishment.service.impl;

import cn.stylefeng.guns.GunsApplication;
import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.modular.basic.model.params.BasicGoodsParam;
import cn.stylefeng.guns.modular.basic.model.result.BasicGoodsResult;
import cn.stylefeng.guns.modular.basic.service.BasicGoodsService;
import cn.stylefeng.guns.modular.replenishment.entity.ReplenishmentOrder;
import cn.stylefeng.guns.modular.replenishment.mapper.ReplenishmentOrderMapper;
import cn.stylefeng.guns.modular.replenishment.model.params.ReplenishmentOrderParam;
import cn.stylefeng.guns.modular.replenishment.model.result.BHStorageStockResult;
import cn.stylefeng.guns.modular.replenishment.model.result.ReplenishmentOrderResult;
import  cn.stylefeng.guns.modular.replenishment.service.ReplenishmentOrderService;
import cn.stylefeng.guns.modular.storage.service.StorageStockService;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.guns.sys.modular.system.service.UserService;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.util.concurrent.AtomicDouble;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.io.Serializable;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * <p>
 * 补货单 服务实现类
 * </p>
 *
 * @author wp
 * @since 2025-05-26
 */
@Service
public class ReplenishmentOrderServiceImpl extends ServiceImpl<ReplenishmentOrderMapper, ReplenishmentOrder> implements ReplenishmentOrderService {
    private final static Logger logger = LoggerFactory.getLogger(ReplenishmentOrderServiceImpl.class);

    @Autowired
    private BasicGoodsService basicGoodsService;
    @Autowired
    private ReplenishmentOrderMapper replenishmentOrderMapper;

    @Autowired
    private StorageStockService storageStockService;
    @Autowired
    private UserService userService;

    @Override
    public void add(ReplenishmentOrderParam param){
        ReplenishmentOrder entity = getEntity(param);
        this.save(entity);
    }

    @Override
    public void delete(ReplenishmentOrderParam param){
        this.removeById(getKey(param));
    }

    @Override
    public void update(ReplenishmentOrderParam param){
        ReplenishmentOrder oldEntity = getOldEntity(param);
        ReplenishmentOrder newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);
        this.updateById(newEntity);
    }

    @Override
    public ReplenishmentOrderResult findBySpec(ReplenishmentOrderParam param){
        return null;
    }

    @Override
    public List<ReplenishmentOrderResult> findListBySpec(ReplenishmentOrderParam param){
        return this.baseMapper.customList(param);
    }

    @Override
    public LayuiPageInfo findPageBySpec(ReplenishmentOrderParam param,String condition){
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.customPageList(pageContext, param,condition);
        return LayuiPageFactory.createPageInfo(page);
    }



    private Serializable getKey(ReplenishmentOrderParam param){
        return param.getId();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private ReplenishmentOrder getOldEntity(ReplenishmentOrderParam param) {
        return this.getById(getKey(param));
    }

    private ReplenishmentOrder getEntity(ReplenishmentOrderParam param) {
        ReplenishmentOrder entity = new ReplenishmentOrder();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }


    /**
     * 生成补货单
     * @return
     */
    @Override
    public ResponseData generateReplenishmentOrder(String goodsNumber,String goodsCount) {


        User user  = userService.getById(1922549817034559490L);
        Long deptId = user.getDeptId();
        // 1. 是否触发补货 出库数量大于拣货位数量 + 待补货数量
        // 1.1. 拣货位库存数量
        int replenishmentOrder = this.baseMapper.getReplenishmentOrder(goodsNumber,96);
        // 1.2. 待补货数量
        int pendingReplenishmentOrder = this.baseMapper.getPendingReplenishmentOrder(goodsNumber,1922549501895528450l);
        // 1.3. 出库数量
        String djhCount = storageStockService.getDjhCountByGoodsNumber(goodsNumber,deptId);

        logger.info("生成补货单：商品编号：{}，商品数量：{}， 拣货位库存数量：{}，待补货数量：{}",goodsCount, goodsNumber, replenishmentOrder, pendingReplenishmentOrder);
        if (Double.valueOf(goodsCount) <= pendingReplenishmentOrder + replenishmentOrder - Double.valueOf(djhCount)) {    // 无须补货
            return ResponseData.success();
        }

        // 1.2. 订单商品数量
        // 3.1 查询该商品的所有库存

        BasicGoodsParam basicGoodsParam = new BasicGoodsParam();
        basicGoodsParam.setGoodsNumber(goodsNumber);
        BasicGoodsResult basicGoodsResult = basicGoodsService.findBySpec(basicGoodsParam, 1922549501895528450l);     // 1922549501895528450l  公司id
        if (basicGoodsResult == null) {
            return ResponseData.success("该商品不存在");
        }

        // 1. 根据goods_number获取 拣货位库存商品库存量
        Double replenishmentQuantity = 0.0;// 需要补的数量

//        BasicGoodsParam param = new BasicGoodsParam();
//        param.setGoodsNumber(goodsNumber);
//        BasicGoodsResult bySpec = basicGoodsService.findBySpec(param, 1922549501895528450l);
        // 2. 根据goods_number近七天销售平均值
        int averageSale = this.baseMapper.getAverageSale(goodsNumber);

        // 2.1 计算出补货数量

        if (averageSale < replenishmentOrder && Double.valueOf(goodsCount) <= pendingReplenishmentOrder + replenishmentOrder - Double.valueOf(djhCount)) {
            return ResponseData.success("该商品近七天销售量小于拣货位库存量，无需补货");
        }else {
            // 3.1 计算出补货数量
            replenishmentQuantity = (double) (averageSale*2 - replenishmentOrder);

            replenishmentQuantity = replenishmentQuantity > Double.valueOf(goodsCount) ? replenishmentQuantity : Double.valueOf(goodsCount);
            // 3.2 根据goods_number查找商品箱规
//            Integer boxQuantity = this.baseMapper.getBoxQuantity(goodsNumber);
//            if (boxQuantity != null || boxQuantity !=0){   // 箱规不为空，则补货数量为箱规
//            // 3.3 计算出补货数量
//                if (replenishmentQuantity % boxQuantity != 0){
//                    replenishmentQuantity = (replenishmentQuantity / boxQuantity) * boxQuantity + boxQuantity;
//                }else {
//                    replenishmentQuantity = (replenishmentQuantity / boxQuantity) * boxQuantity;
//                }
//            }
            // 3.4 生成补货单
            // 3.4.1 查询该商品的所有库存
            List<BHStorageStockResult> storageStockResults = basicGoodsService.findStorageStockByGoodsNumber("存储位",goodsNumber, 1922549501895528450l);
            List<BHStorageStockResult> storageStockResults1 = basicGoodsService.findStorageStockByGoodsNumber("拣货位",goodsNumber, 1922549501895528450l);

            // 3.4.2 计算出补货数量
            AtomicDouble finalReplenishmentQuantity = new AtomicDouble(replenishmentQuantity);
            for (BHStorageStockResult stock : storageStockResults) {
                if (finalReplenishmentQuantity.get() > Double.valueOf(stock.getNum())) {
                    final String[] positionNumber = {""};
                    if (storageStockResults.size() > 0) {
                        //库位名称(拣货位)
                        storageStockResults1.stream()
                                .filter(s -> s.getGoodsNumber().equals(stock.getGoodsNumber())
//                                        && s.getGoodsbatchs().equals(stock.getGoodsbatchs())
                                )
                                .findFirst()
                                .ifPresent(s -> positionNumber[0] = s.getPositionNumber());

                    }

                    double v = finalReplenishmentQuantity.get() - Double.valueOf(stock.getNum());
                    int vintage   = (int) v;
                    finalReplenishmentQuantity.set(vintage);

                    ReplenishmentOrder replenishmentOrderEntity = new ReplenishmentOrder();
                    replenishmentOrderEntity.setGoodsNumber(goodsNumber);
                    replenishmentOrderEntity.setGoodsName(basicGoodsResult.getGoodsName());
                    replenishmentOrderEntity.setNumb(stock.getNum());
                    //库位名称(拣货位)
                    if (positionNumber[0] != null) {
                        replenishmentOrderEntity.setJpositionName(positionNumber[0]);
                        //库位编号(拣货位)
                        replenishmentOrderEntity.setJpositionNumber(positionNumber[0]);
                    }

                    //库位名称(存储位)
                    replenishmentOrderEntity.setPositionName(stock.getPositionNumber());
                    //库位编号(存储位)
                    replenishmentOrderEntity.setPositionNumber(stock.getPositionNumber());
                    replenishmentOrderEntity.setStatus("待补货");
                    replenishmentOrderEntity.setGoodsCustomerId(1922549501895528450l);
                    replenishmentOrderEntity.setStoreId(stock.getId()+"");
                    replenishmentOrderMapper.saveReplenishmentOrder(replenishmentOrderEntity);
                } else {
//                    List<BHStorageStockResult> storageStockResults1 = basicGoodsService.findStorageStockByGoodsNumber("拣货位",goodsNumber, 1922549501895528450l);
                    final String[] positionNumber = {""};
                    if (storageStockResults1.size() > 0) {
                        //库位名称(拣货位)
//                        positionNumber = storageStockResults1.get(0).getPositionNumber();
                        storageStockResults1.stream()
                                .filter(s -> s.getGoodsNumber().equals(stock.getGoodsNumber())
//                                        && s.getGoodsbatchs().equals(stock.getGoodsbatchs())
                                )
                                .findFirst()
                                .ifPresent(s -> positionNumber[0] = s.getPositionNumber());
                    }
                    ReplenishmentOrder replenishmentOrderEntity = new ReplenishmentOrder();
                    replenishmentOrderEntity.setGoodsNumber(goodsNumber);
                    replenishmentOrderEntity.setGoodsName(basicGoodsResult.getGoodsName());
                    replenishmentOrderEntity.setNumb(String.valueOf(finalReplenishmentQuantity.get()));
                    //库位名称(拣货位)
                    if (positionNumber[0] != null) {
                        replenishmentOrderEntity.setJpositionName(positionNumber[0]);
                        //库位编号(拣货位)
                        replenishmentOrderEntity.setJpositionNumber(positionNumber[0]);
                    }
                    //库位名称(存储位)
                    replenishmentOrderEntity.setPositionName(stock.getPositionNumber());
                    //库位编号(存储位)
                    replenishmentOrderEntity.setPositionNumber(stock.getPositionNumber());
                    replenishmentOrderEntity.setStatus("待补货");
                    replenishmentOrderEntity.setGoodsCustomerId(1922549501895528450l);
                    replenishmentOrderEntity.setStoreId(stock.getId()+"");
                    replenishmentOrderMapper.saveReplenishmentOrder(replenishmentOrderEntity);
                    finalReplenishmentQuantity.set(0);
                    break;
                }
            }
        }
        return ResponseData.success();
    }


    /**
     * 武汉仓补货
     * @param goodsNumber
     * @param goodsCount
     * @return
     */
    @Override
    public ResponseData generateWhReplenishmentOrder(String goodsNumber, String goodsCount) {


        //武汉仓管理员
        User user  = userService.getById(1970704316458569730L);
        Long deptId = user.getDeptId();
        // 1. 是否触发补货 出库数量大于拣货位数量 + 待补货数量
        // 1.1. 拣货位库存数量
        int replenishmentOrder = this.baseMapper.getReplenishmentOrder(goodsNumber,122);
        // 1.2. 待补货数量
        int pendingReplenishmentOrder = this.baseMapper.getPendingReplenishmentOrder(goodsNumber,1970694108227276802l);
        // 1.3. 出库数量
        String djhCount = storageStockService.getDjhCountByGoodsNumber(goodsNumber,deptId);

        logger.info("生成补货单：商品编号：{}，商品数量：{}， 拣货位库存数量：{}，待补货数量：{}",goodsCount, goodsNumber, replenishmentOrder, pendingReplenishmentOrder);
        if (Double.valueOf(goodsCount) <= pendingReplenishmentOrder + replenishmentOrder - Double.valueOf(djhCount)) {    // 无须补货
            return ResponseData.success();
        }

        // 1.2. 订单商品数量
        // 3.1 查询该商品的所有库存

        BasicGoodsParam basicGoodsParam = new BasicGoodsParam();
        basicGoodsParam.setGoodsNumber(goodsNumber);
        BasicGoodsResult basicGoodsResult = basicGoodsService.findBySpec(basicGoodsParam, 1970694108227276802l);     // 1970694108227276802l  公司id
        if (basicGoodsResult == null) {
            return ResponseData.success("该商品不存在");
        }

        // 1. 根据goods_number获取 拣货位库存商品库存量
        Double replenishmentQuantity = 0.0;// 需要补的数量

//        BasicGoodsParam param = new BasicGoodsParam();
//        param.setGoodsNumber(goodsNumber);
//        BasicGoodsResult bySpec = basicGoodsService.findBySpec(param, 1970694108227276802l);
        // 2. 根据goods_number近七天销售平均值
        int averageSale = this.baseMapper.getAverageSale(goodsNumber);

        // 2.1 计算出补货数量

        if (averageSale < replenishmentOrder && Double.valueOf(goodsCount) <= pendingReplenishmentOrder + replenishmentOrder - Double.valueOf(djhCount)) {
            return ResponseData.success("该商品近七天销售量小于拣货位库存量，无需补货");
        }else {
            // 3.1 计算出补货数量
            replenishmentQuantity = (double) (averageSale*2 - replenishmentOrder);

            replenishmentQuantity = replenishmentQuantity > Double.valueOf(goodsCount) ? replenishmentQuantity : Double.valueOf(goodsCount);
            // 3.2 根据goods_number查找商品箱规
//            Integer boxQuantity = this.baseMapper.getBoxQuantity(goodsNumber);
//            if (boxQuantity != null || boxQuantity !=0){   // 箱规不为空，则补货数量为箱规
//            // 3.3 计算出补货数量
//                if (replenishmentQuantity % boxQuantity != 0){
//                    replenishmentQuantity = (replenishmentQuantity / boxQuantity) * boxQuantity + boxQuantity;
//                }else {
//                    replenishmentQuantity = (replenishmentQuantity / boxQuantity) * boxQuantity;
//                }
//            }
            // 3.4 生成补货单
            // 3.4.1 查询该商品的所有库存
            List<BHStorageStockResult> storageStockResults = basicGoodsService.findStorageStockByGoodsNumber("存储位",goodsNumber, 1970694108227276802l);
            List<BHStorageStockResult> storageStockResults1 = basicGoodsService.findStorageStockByGoodsNumber("拣货位",goodsNumber, 1970694108227276802l);

            // 3.4.2 计算出补货数量
            AtomicDouble finalReplenishmentQuantity = new AtomicDouble(replenishmentQuantity);
            for (BHStorageStockResult stock : storageStockResults) {
                if (finalReplenishmentQuantity.get() > Double.valueOf(stock.getNum())) {
                    final String[] positionNumber = {""};
                    if (storageStockResults.size() > 0) {
                        //库位名称(拣货位)
                        storageStockResults1.stream()
                                .filter(s -> s.getGoodsNumber().equals(stock.getGoodsNumber())
//                                        && s.getGoodsbatchs().equals(stock.getGoodsbatchs())
                                )
                                .findFirst()
                                .ifPresent(s -> positionNumber[0] = s.getPositionNumber());

                    }

                    double v = finalReplenishmentQuantity.get() - Double.valueOf(stock.getNum());
                    int vintage   = (int) v;
                    finalReplenishmentQuantity.set(vintage);

                    ReplenishmentOrder replenishmentOrderEntity = new ReplenishmentOrder();
                    replenishmentOrderEntity.setGoodsNumber(goodsNumber);
                    replenishmentOrderEntity.setGoodsName(basicGoodsResult.getGoodsName());
                    replenishmentOrderEntity.setNumb(stock.getNum());
                    //库位名称(拣货位)
                    if (positionNumber[0] != null) {
                        replenishmentOrderEntity.setJpositionName(positionNumber[0]);
                        //库位编号(拣货位)
                        replenishmentOrderEntity.setJpositionNumber(positionNumber[0]);
                    }

                    //库位名称(存储位)
                    replenishmentOrderEntity.setPositionName(stock.getPositionNumber());
                    //库位编号(存储位)
                    replenishmentOrderEntity.setPositionNumber(stock.getPositionNumber());
                    replenishmentOrderEntity.setStatus("待补货");
                    replenishmentOrderEntity.setGoodsCustomerId(1970694108227276802l);
                    replenishmentOrderEntity.setStoreId(stock.getId()+"");
                    replenishmentOrderMapper.saveReplenishmentOrder(replenishmentOrderEntity);
                } else {
//                    List<BHStorageStockResult> storageStockResults1 = basicGoodsService.findStorageStockByGoodsNumber("拣货位",goodsNumber, 1970694108227276802l);
                    final String[] positionNumber = {""};
                    if (storageStockResults1.size() > 0) {
                        //库位名称(拣货位)
//                        positionNumber = storageStockResults1.get(0).getPositionNumber();
                        storageStockResults1.stream()
                                .filter(s -> s.getGoodsNumber().equals(stock.getGoodsNumber())
//                                        && s.getGoodsbatchs().equals(stock.getGoodsbatchs())
                                )
                                .findFirst()
                                .ifPresent(s -> positionNumber[0] = s.getPositionNumber());
                    }
                    ReplenishmentOrder replenishmentOrderEntity = new ReplenishmentOrder();
                    replenishmentOrderEntity.setGoodsNumber(goodsNumber);
                    replenishmentOrderEntity.setGoodsName(basicGoodsResult.getGoodsName());
                    replenishmentOrderEntity.setNumb(String.valueOf(finalReplenishmentQuantity.get()));
                    //库位名称(拣货位)
                    if (positionNumber[0] != null) {
                        replenishmentOrderEntity.setJpositionName(positionNumber[0]);
                        //库位编号(拣货位)
                        replenishmentOrderEntity.setJpositionNumber(positionNumber[0]);
                    }
                    //库位名称(存储位)
                    replenishmentOrderEntity.setPositionName(stock.getPositionNumber());
                    //库位编号(存储位)
                    replenishmentOrderEntity.setPositionNumber(stock.getPositionNumber());
                    replenishmentOrderEntity.setStatus("待补货");
                    replenishmentOrderEntity.setGoodsCustomerId(1970694108227276802l);
                    replenishmentOrderEntity.setStoreId(stock.getId()+"");
                    replenishmentOrderMapper.saveReplenishmentOrder(replenishmentOrderEntity);
                    finalReplenishmentQuantity.set(0);
                    break;
                }
            }
        }
        return ResponseData.success();
    }

    public static void main(String[] args) {
        int replenishmentOrder = 10;//拣货位上数量
        int averageSale = 100;//七天平均
        int goodsCount = 20;//需要补货数量
        int replenishmentQuantity= 0;
        replenishmentQuantity = averageSale*2 - replenishmentOrder;

        replenishmentQuantity = replenishmentQuantity > Integer.valueOf(goodsCount) ? replenishmentQuantity : Integer.valueOf(goodsCount);


        //System.out.println(replenishmentQuantity);
    }

}
